import { _decorator, CCInteger, Collider2D, Component, Contact2DType, IPhysics2DContact, Node, Prefab, Sprite, Vec2 } from 'cc';
import { GameManager } from './GameManager';
import { Utils } from './common/CocosUtils';
import { global } from './common/Global';
import { eventManager } from './common/EventManager';
import { GameState } from './constants/GameConstants';
const { ccclass, property } = _decorator;

@ccclass('Box')
export class Box extends Component {

    @property({type: CCInteger})
    public hp: number = 10;
    private collider: Collider2D = null;

    start() {
        // 注册单个碰撞体的回调函数
         this.collider = this.getComponent(Collider2D);
         if (this.collider) {
            this.collider.on(Contact2DType.BEGIN_CONTACT, this.onCollisionEnter, this);
         }
    }

    // 碰撞检测回调
    onCollisionEnter(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
        // 当两个碰撞器开始接触时触发此函数
        // console.log('碰撞的对象:' , selfCollider.node.name,otherCollider.node.name );
        this.hit(selfCollider)
    }
 

       
    setHp(hp: number) {
        this.hp = hp;
    }
    getHp() {
        return this.hp;
    }

    hit(self: Collider2D) {
        if (this.hp <= 0) {
            return;
        }
        this.hp -= 1
        GameManager.Instance.genSpark(self.node)
        if (this.hp == 0) {
            // 切换切图
            const name = this.node.getComponent(Sprite).spriteFrame.name
            Utils.setSpriteAtlas(this.node, 'plist/box', name + '_1')
            // 延迟执行
            setTimeout(() => {
                global.enemyCount--;
                this.tryAward();
                this.tryProp();
                GameManager.Instance.delPrefab(this.node, 1)
            }, 1000);
        }
    }

    /**
     * 按几率生成道具
     */
    tryProp(){
        let num = Math.random() * 100 //生成道具概率
        if(num < 50){  
            const type = Utils.randomInt(1, 3)//生成哪种道具
            // console.log("触发生成道具：" + type)
            GameManager.Instance.createProp(this.node, type)
        }
    }

     /**
     * 生成奖励
     */
    tryAward(){
        let num = Math.random() * 100   
        if(num > 80){
            GameManager.Instance.setGameState(GameState.GS_STOP)
            eventManager.emit("ui:award", {active:true})
        }else{
            eventManager.emit("ui:head", {
                worldPos: this.node,
                dstPos: new Vec2(0, 0),
                radius: 100,
                goldCount: 6,
                addGold: 100
            })
        }
    }
    
    
 
}

